package com.monkeygroup.mygoplus.http;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.monkeygroup.mygoplus.MyGoApplication;

public class CustomStringRequest extends StringRequest {
    private Map<String, String> mParams;

    public CustomStringRequest(int method, String url, Map<String, String> params, Listener<String> responseListener, ErrorListener errorListener) {
        super(method, url, responseListener, errorListener);
        this.mParams = params;
    }

    @Override
    protected Response<String> parseNetworkResponse(
            NetworkResponse response) {
        String parsed, charsetCode;

        try {
            charsetCode = HttpHeaderParser.parseCharset(response.headers);
            if (charsetCode.equals("ISO-8859-1")) {
                charsetCode = "UTF-8";
            }
            parsed = new String(response.data, charsetCode);
        } catch (UnsupportedEncodingException var4) {
            parsed = new String(response.data);
        }

        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParams;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        if (MyGoApplication.token != null && !MyGoApplication.token.equals("")) {
            Map<String, String> headers = new HashMap<>();
            headers.put("token", MyGoApplication.token);

            return headers;
        } else {
            return super.getHeaders();
        }

    }

}
